package com.yunshipei.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import java.util.concurrent.atomic.AtomicInteger;

import io.rong.app.model.IFilterModel;

/**
 * Created by cike on 16/9/9.
 */
public class EnterplorerManager {
    private AtomicInteger mOpenCounter = new AtomicInteger();
    private static EnterplorerManager instance;
    private static EnterplorerHelper enterplorerHelper;
    private SQLiteDatabase mDatabase;

    public static synchronized void initalizeInstance(Context context) {
        if (instance == null) {
            synchronized (EnterplorerManager.class) {
                instance = new EnterplorerManager();
                enterplorerHelper = new EnterplorerHelper(context);
            }
        }
    }

    public static synchronized EnterplorerManager  getInstance(Context context) {
        if (instance == null)
            initalizeInstance(context);
        return instance;
    }

    public synchronized SQLiteDatabase getWritableDatabase() {
        if (mOpenCounter.incrementAndGet() == 1) {
            mDatabase = enterplorerHelper.getWritableDatabase();
        }
        return mDatabase;
    }

    public synchronized SQLiteDatabase getReadableDatabase() {
        if ( mOpenCounter.incrementAndGet() == 1) {
            mDatabase = enterplorerHelper.getReadableDatabase();
        }
        return mDatabase;
    }

    public synchronized void CloseDatabase() {
        if (mOpenCounter.decrementAndGet() == 0) {
            mDatabase.close();
        }
    }

    public EnterplorerHelper getEnterplorerHelper() {
        return enterplorerHelper;
    }
}
